package com.seanzx.dp.common;

import com.seanzx.common.Lists;
import com.seanzx.common.Pair;
import com.seanzx.common.Result;
import com.seanzx.common.ResultCode;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;

public class DBProperties {
    private static Properties PROPERTIES;

    public static void init() {
        if (PROPERTIES != null) {
            return;
        }
        PROPERTIES = new Properties();
        System.out.println("=====init properties start=====");
        try {
            File properties = Persist.properties();
            if (!properties.exists()) {
                properties.createNewFile();
                PROPERTIES.load(new FileInputStream(properties));
                initProperties();
            } else {
                PROPERTIES.load(new FileInputStream(properties));
            }
        System.out.println("=====init properties end=====");
        } catch (IOException e) {
            System.err.println("load properties failed");
        }
    }

    public static Result<?> get(String key) {
        String property = PROPERTIES.getProperty(key);
        if (property == null) {
            return Result.of(ResultCode.NO_SUCH_PROPERTY);
        }
        return Result.ok(property);
    }

    public static Result<?> set(String key, String value) {
        if (PROPERTIES.getProperty(key) == null) {
            return Result.of(ResultCode.NO_SUCH_PROPERTY);
        }
        PROPERTIES.setProperty(key, value);
        try {
            PROPERTIES.store(new FileOutputStream(Persist.properties()), null);
        } catch (IOException e) {
            System.err.println("store properties failed");
        }
        return Result.ok();
    }

    private static void initProperties() {
        PROPERTIES.setProperty("table_persist_page_size", "500");

        try {
            PROPERTIES.store(new FileOutputStream(Persist.properties()), null);
        } catch (IOException e) {
            System.err.println("store properties failed");
        }
    }

    public static Result<Set<String>> names() {
        Set<String> names = PROPERTIES.stringPropertyNames();
        return Result.ok(names);
    }

    public static Result<Set<String>> names(String key) {
        Set<String> names = PROPERTIES.stringPropertyNames();
        names = names.stream().filter(name -> name.contains(key)).collect(Collectors.toSet());
        return Result.ok(names);
    }

    public static void main(String[] args) {
        Result<?> table_persist_page_size = DBProperties.get("table_persist_page_size");
        System.out.println(table_persist_page_size.getData());
    }
}
